<?php
/**
 * created by zzy
 * date: 2018/1/26 14:07
 */
namespace App\Api\Service\Stock\Controllers;

use App\Eloquent\Ygt\CategoryFields;
use App\Eloquent\Ygt\DepartmentUser;
use App\Eloquent\Ygt\Product;
use App\Eloquent\Ygt\ProductFields;
use App\Eloquent\Ygt\Qrcode;
use App\Eloquent\Ygt\Stock;
use App\Eloquent\Ygt\StockFields;
use App\Eloquent\Ygt\StockIn;
use App\Engine\Func;
use App\Engine\KmPrinter;
use Framework\BaseClass\Api\Controller;

class WaterController extends Controller
{
    public $userId      = 25;
    public function add()
    {
        $userId             = Func::getHeaderValueByName( 'userid',$this->userId );
        $userInfo           = DepartmentUser::getCurrentInfo( $userId );
        //材料自段
        $productId          = request('product_id','');
        $number             = request('number',0);
        //材料流水字段
        $unitPrice          = request('unit_price',0);
        $distributionCompany= request('distribution_company','');
        $distributionTime   = request('distribution_time','');
        $contactNumber      = request('contact_number','');
        $remark             = request('remark','');
        $whoName            = request('who_name','');
        $placeName          = request('place_name','');
        $distributionTimeInt    = 0;
        if($distributionTime)
        {
            $distributionTimeInt    = strtotime($distributionTime);
        }
        //是否属于客户
        $isCustomer         = request('is_customer',1);
        $customerId         = request('customer_id',0);
        if($isCustomer == 0)
        {
            $customerId     = 0;
        }else{
            if($customerId == 0){
                $isCustomer = 0;
            }
        }
        //是否是打印入库
        $isPrint            = request('is_print',0);
        if(!$userId || !$productId )
        {
            xThrow( ERR_PARAMETER );
        }
        $requestMustArr     = [
            'number'=>'数量不能为空',
        ];
        $requestData            = request()->all();
        foreach($requestMustArr as $key=>$val)
        {
            if(!isset($requestData[$key]) || empty($requestData[$key]))
            {
                $requestMustMsg     = $val;
                xThrow( ERR_PARAMETER,$requestMustMsg );
            }
        }
        $companyId          = $userInfo->company_id;
        //核对资料的一些信息
        $where              = ['id'=>$productId];
        $product            = Product::getInfo($where);
        if(!$product)
        {
            xThrow( ERR_PARAMETER );
        }
        if(empty($placeName))
        {
            $placeName      = $product->place_name;
        }
        //非标属性在指定的范围内时才能通过
        //不管产品是否存在都需比较后才能入库
        $nonFieldsResult    = true;
        $nonFieldsResultArr = [];
        //非标属性提交过来的值
        $requestNonArr          = request('non_arr');
        $nonArr                 = json_decode(htmlspecialchars_decode($requestNonArr), true);
        $where                  = ['type'=>2,'product_id'=>$productId];
        $nonstandardArr         = ProductFields::getList($where)->toArray();
        if($nonArr)
        {
            foreach($nonArr as $key=>$val)
            {
                $valFieldName           = $val['field_name'];
                $valFieldValue          = $val['field_value'];
                $valFieldValue          = intval($valFieldValue);
                foreach($nonstandardArr as $k=>$v)
                {
                    $vIsMust            = $v['is_must'];
                    $vFieldName         = $v['field_name'];
                    $vMinValue          = $v['min_value'];
                    $vMaxValue          = $v['max_value'];
                    if($valFieldName == $vFieldName)
                    {
                        //$fieldUnit      = $v['unit'];
                        if($valFieldValue < $vMinValue || $valFieldValue > $vMaxValue)
                        {
                            $nonFieldsResult        = false;
                            $nonFieldsResultArr[]   = $valFieldName.'不在范围内';
                        }
                        if($vIsMust==1 && !$valFieldValue)
                        {
                            $nonFieldsResult        = false;
                            $nonFieldsResultArr[]   = $valFieldName.'必填';
                        }
                    }
                }
                //$nonArr[$key]['field_unit']     = $fieldUnit;
            }
        }
        if($nonFieldsResult === false)
        {
            $nonFieldsResultMessage     = implode(',',$nonFieldsResultArr);
            xThrow(ERR_PARAMETER, $nonFieldsResultMessage);
        }

        //开始入库--ygt_stockin
        $stockInData        = [
            'unit_price'=> $unitPrice,
            'distribution_company' => $distributionCompany,
            'distribution_time' => $distributionTimeInt,
            'contact_number' => $contactNumber,
            'uid' => $userId,
        ];
        $stockInId          = StockIn::insertOneData($stockInData,'id');

        //每次入库的非标属性是可以不一样的
        //--ygt_stock_fields
        $qrcodeFieldsData           = [];
        if($nonArr && $stockInId)
        {
            foreach($nonArr as $key=>$val)
            {
                $valFieldName       = $val['field_name'];
                $valFieldValue      = $val['field_value'];
                $valFieldUnit       = isset($val['unit']) ? $val['unit'] : '';
                $valFieldValue      = strval($valFieldValue);
                $stockFieldData     = [
                    'table_name'=>'stockin',
                    'table_id' => $stockInId,
                    'field_id' => 0,
                    'field_name' => $valFieldName,
                    'field_value' => $valFieldValue,
                    'field_unit' => $valFieldUnit,
                ];
                StockFields::insertOneData($stockFieldData);
                $temp               = [
                    'field_name'=>$valFieldName,
                    'field_value'=>$valFieldValue,
                    'field_unit'=>$valFieldUnit,
                ];
                $qrcodeFieldsData[] = $temp;
            }
        }
        //--ygt_stock
        $waterNo            = \App\Engine\Stock::createWaterNo();
        $relateType         = 3;
        $stockData          = [
            'company_id'=>$companyId,
            'water_no' => $waterNo,
            'relate_type' => $relateType,
            'relate_id' => $stockInId,
            'product_id' => $productId,
            'number' => $number,
            'total_price' => $number*$unitPrice,
            'operate_uid' => $userId,
            'remark' => $remark,
            'is_customer' => $isCustomer,
            'customer_id' => $customerId,
            'who_name' => $whoName,
            'place_name' => $placeName,
        ];
        $lastProductNumber  = $product->number;
        $relateType         = \App\Engine\Stock::getRelateType($relateType);
        $stockData['type']          = $relateType['type'];
        $stockData['stock_type']        = $relateType['stock_type'];
        $stockData['last_product_number']       = $lastProductNumber+$stockData['number'];
        $stockId            = Stock::insertOneData($stockData,'id');
        if($stockId===false)
        {
            xThrow(ERR_UNKNOWN);
        }

        //更新材料的库存数量
        $tmpProductObj = \App\Eloquent\Ygt\Product::where('id', $productId)->first();
        $tmpProductObj->increment('number', $number);
        $result             = [ 'msg'=>'ok','product_id'=>$productId];

        //更新材料的计量属性
        $materialComputeNum = \App\Engine\Material::getMaterialComputeNum($productId,$number);
        if($materialComputeNum){
            //获取计量属性字段
            $tmpProductFieldsList = \App\Eloquent\Ygt\ProductFields::where(['assemblage_material_id'=>$tmpProductObj['assemblage_material_id']])->get();
            foreach ($tmpProductFieldsList as $tmpProductFieldsRow){
                if($tmpProductFieldsRow['is_compute']){
                    $tmpObj = \App\Eloquent\Ygt\ProductFieldsCompute::firstOrNew(['material_id'=>$productId,'type'=>1,'product_fields_id'=>$tmpProductFieldsRow['id']]);
                    $tmpObj->material_id = $productId;
                    $tmpObj->type = 1;
                    $tmpObj->product_fields_id = $tmpProductFieldsRow['id'];
                    $tmpObj->number = $tmpObj->number + $materialComputeNum;
                    $tmpObj->save();
                }
            }
        }


        //更新集合材料的库存数量
        $tmpProductRow = $tmpProductObj;
        if($tmpProductRow['assemblage_material_id']){
            $tmpAssemblageMaterialRow = \App\Eloquent\Ygt\AssemblageMaterial::where(['id'=>$tmpProductRow['assemblage_material_id']])->first();
            if($tmpAssemblageMaterialRow){
                $tmpAssemblageMaterialRow->number = $tmpAssemblageMaterialRow->number + $number;
                $tmpAssemblageMaterialRow->save();

                //更新集合材料的计量属性
                if($materialComputeNum){
                    //获取计量属性字段
//                    $tmpProductFieldsList = \App\Eloquent\Ygt\ProductFields::where(['assemblage_material_id'=>$tmpProductObj['assemblage_material_id']])->get();
                    foreach ($tmpProductFieldsList as $tmpProductFieldsRow){
                        if($tmpProductFieldsRow['is_compute']){
                            $tmpObj = \App\Eloquent\Ygt\ProductFieldsCompute::firstOrNew(['material_id'=>$tmpAssemblageMaterialRow['id'],'type'=>2,
                                'product_fields_id'=>$tmpProductFieldsRow['id']]);
                            $tmpObj->material_id = $tmpAssemblageMaterialRow['id'];
                            $tmpObj->type = 2;
                            $tmpObj->product_fields_id = $tmpProductFieldsRow['id'];
                            $tmpObj->number = $tmpObj->number + $materialComputeNum;
                            $tmpObj->save();
                        }
                    }
                }

            }
        }


        //是否是打印入库
        if ($isPrint== 1)
        {
            $printArr       = [
                'stock_id'=>$stockId,
                'stock_number'=>$number,
                'qrcode_fields_data'=>$qrcodeFieldsData,
            ];
            $printResult    = \App\Engine\PrintEngine::productQrcodeByType($productId,$printArr);
            $result['pinfo'] = $printResult;
        }
        return $result;
    }
    //采购录入的信息详情
    public function detail()
    {
        $userId             = Func::getHeaderValueByName( 'userid',$this->userId );
        $userInfo           = DepartmentUser::getCurrentInfo( $userId );
        $stockId            = request('water_id');
        if(!$userInfo || !$stockId)
        {
            xThrow( ERR_PARAMETER );
        }
        $companyId          = $userInfo->company_id;
        $where              = ['company_id'=>$companyId,'user_id'=>$userId];
        $departmentUser     = \App\Eloquent\Ygt\DepartmentUser::getInfo($where);
        $privilegeId        = $departmentUser->privilege_id;
        $isSale             = \App\Eloquent\Ygt\Privilege::getAppnodeId( $privilegeId, 10 );//是否采购员
        $printButton        = 1;
        if($isSale)
        {
            $printButton    = 0;
        }
        $where              = ['id'=>$stockId];
        $columns            = 'id,unit_price,distribution_company,distribution_time,contact_number';
        $info               = StockIn::getInfo($where,$columns);
        if(!$info)
        {
            xThrow( ERR_PARAMETER );
        }
        $where              = ['relate_type'=>3, 'relate_id'=>$stockId];
        $stockInfo          = Stock::getInfo($where);
        //$distributionTime   = '';
        if($info->distribution_time)
        {
            //$distributionTime   = date('Y-m-d H:i:s', $info->distribution_time);
        }
        $stockInfoArr       = $stockInfo->toArray();
        $createdAtYmd       = date('Y-m-d',$stockInfoArr['created_at']);
        $data               = [
            ['field_name'=>'入库时间','field_value'=>$createdAtYmd],
            ['field_name'=>'数量','field_value'=>$stockInfo->number],
            ['field_name'=>'堆位','field_value'=>$stockInfo->place_name],
        ];
        //材料基本属性的自定义字段
//        $productId          = $stockInfo->product_id;
//        $where              = ['product_id'=>$productId];
//        $columns            = 'id,field_name,field_type,varchar,numerical';
//        $customFields       = ProductFields::getList($where,$columns)->toArray();
//        $where              = ['id'=>$productId];
//        $productInfo        = Product::getInfo($where);
//        $categoryId         = $productInfo->category_id;
//        $categoryFields     = CategoryFields::getFieldListByType($categoryId);
//        foreach($categoryFields as $key=>$val)
//        {
//            foreach($customFields as $k=>$v)
//            {
//                if($val['type'] == 1 && $val['field_name'] == $v['field_name'])
//                {
//                    if($v['field_type'] == 1){
//                        $fieldValue = $v['varchar'];
//                    }else{
//                        $fieldValue = $v['numerical'];
//                    }
//                    $data[]         = ['field_name'=>$v['field_name'],'field_value'=>$fieldValue];
//                }
//            }
//        }
        //材料非标字段
        $where              = ['table_name'=>'stockin','table_id'=>$stockId];
        $columns            = 'field_name,field_value,field_unit';
        $stockFields        = StockFields::getList($where,$columns)->toArray();
        foreach($stockFields as $key=>$val)
        {
            $fieldValue     = $val['field_value'].$val['field_unit'];
            $data[]         = ['field_name'=>$val['field_name'],'field_value'=>$fieldValue];
        }

        $imgUrl             = url('api/service/common/qrcode?type=2&id='.$stockInfo->id);
        $result             = [
            'title'=>'材料','data'=>$data,'img_url'=>$imgUrl,'print_button'=>$printButton
        ];
        return $result;
    }
}